const express = require('express'),
    domain = require('domain'),
    bodyParser = require('body-parser'),
    session = require('express-session'),
    compression = require('compression'),
    helmet = require('helmet'),
    path = require('path'),
    multer = require('multer'),
    //fs = require('fs'),
    ueditor = require("ueditor"),
    config = require('./config-local'),
    app = express();
// var serveStatic = require('serve-static');

//单文件上传
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, config.staticPath + "/static/document/"); //保存文件到document文件夹下(设置上传文件的路径)
    },
    filename: function (req, file, cb) { //设置文件夹下所有的文件的文件名称
        var ext = path.extname(file.originalname); //设置文件的的后缀名
        cb(null, file.originalname + "." + ext); //originalname用户计算机上文件的名称,fieldname在窗体上指定的字段名
        console.log(file.originalname + "*****" + ext);
    }
});

const upload = multer({
    storage: storage
}).single("myfile");

//引入一个domain的中间件，将每一个请求都包裹在一个独立的domain中
//domain来处理异常
app.use((req, res, next) => {
    var d = domain.create();
    //监听domain的错误事件
    d.on('error', (err) => {
        console.error(err);
        res.statusCode = 500;
        res.json({
            result: -1,
            msg: '服务器异常'
        });
    });

    d.add(req);
    d.add(res);
    d.run(next);
});

app.use(helmet({
    frameguard: false
}));
app.use(compression({
    level: 9
}));

app.use(bodyParser.json({
    limit: '50mb'
}));
app.use(bodyParser.text({
    limit: '50mb',
    extended: true
}));
app.use(bodyParser.raw({
    limit: '50mb',
    type: 'application/octet-stream'
}));
app.set('trust proxy', 1); // trust first proxy 

app.use(session({
    secret: 'MakeLouden.AREyeShot',
    resave: true,
    rolling: true,
    saveUninitialized: true,
    cookie: {
        // secure: true,
        httpOnly: true,
        // maxAge: 30 * 24 * 60 * 60 * 1000
        // maxAge: 1000 * 5,
        maxAge: 1000 * 60 * 60
    }
}));
var maxAge = config.httpCacheMaxAge; // 1000 * 60 * 60;
app.use(express.static(config.staticPath, {
    maxAge: maxAge,
    setHeaders: setCustomCacheControl
}));

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use("/ueditor/ue", ueditor(path.join(config.staticPath, 'static'), function (req, res, next) {
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var userId = userInfo.id,
            ActionType = req.query.action,
            imgDir = '/ueditor/img/' + userId //默认上传地址为图片
        if (ActionType === 'uploadimage' || ActionType === 'uploadfile' || ActionType === 'uploadvideo') {
            var file_url = imgDir;
            if (ActionType === 'uploadfile') {
                file_url = '/ueditor/file/' + userId; //附件保存地址
            } else if (ActionType === 'uploadvideo') {
                file_url = '/ueditor/video/' + userId; //视频保存地址
            }
            res.ue_up(file_url);
            res.setHeader('Content-Type', 'text/html');
        } else if (ActionType === 'listimage') { //客户端发起图片列表请求
            res.ue_list(imgDir); // 客户端列出目录下的所有图片
        } else { // 客户端发起其它请求
            res.setHeader('Content-Type', 'application/json');
            res.redirect('/ueditor/ueditor.config.json');
            // res.redirect('/classes/noatin_editor_classes/third-party/ueditor1_4_3_3/jsp/config.json');
        }
    } else {
        res.status(401);
        res.end();
    }
}));

app.use('/3rd', require('./thirdparty'))
const shareService = require('./share/shareService'),
    userService = require('./user/userService'),
    courseService = require('./course/courseService'),
    projectService = require('./project/projectService'),
    compileService = require('./code/codeCompileService');

app.get('/s', function (req, res) {
    res.send(JSON.stringify({
        result: 0,
        id: req.sessionID
    }));
});

app.post("/share/create", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var content = req.body.content;
    if (content.length > 20 * 1024 * 1024) {
        var ret = {
            result: -1,
            msg: "文件大小超过限制，上限为20MB"
        };
        res.send(JSON.stringify(
            ret
        ));
    } else {
        var userId;
        var userInfo = req.session.userInfo;
        if (userInfo) {
            userId = userInfo.id;
        }
        shareService.createShare(userId, content, req.body.thumbnail, function (ret) {
            res.send(JSON.stringify(
                ret
            ));
        });
    }
});

app.get("/share/:anonymousShareId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    // res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET,HEAD, PUT, POST, PATCH,DELETE,OPTIONS");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var hexId = req.params.anonymousShareId,
        numberId = parseInt(hexId, 16);
    shareService.getShareById(numberId, function (ret) {
        res.send(JSON.stringify(ret));
    });
});

app.get("/share/createCourseShareByPid/:pid", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var projId = req.params.pid;
    var userInfo = req.session.userInfo;
    if (userInfo) {
        if (projId) {
            var userId = userInfo.id;
            shareService.createCourseShareByPid(userId, projId, function (ret) {
                res.send(JSON.stringify(
                    ret
                ));
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "不存在该工程"
            }));
        }
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

app.get("/courseShare/:shareId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    // res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET,HEAD, PUT, POST, PATCH,DELETE,OPTIONS");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var hexId = req.params.shareId,
        numberId = parseInt(hexId, 16);
    shareService.getCourseShareById(numberId, function (ret) {
        res.send(JSON.stringify(ret));
    });
});
//由客户端通知服务器登录
app.post("/user/setState", function (req, res) {
    console.log("setState " + req.sessionID);
    var userInfo = req.body;
    userService.setUserState(req, userInfo, function (ret) {
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify(ret));
    });
});

app.get("/user/getState", function (req, res) {
    userService.getUserState(req, res);
});

app.post("/user/clearState", function (req, res) {
    console.log("clearState " + req.sessionID);
    userService.setUserState(req, null, function (result, msg) {
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify({
            result: result,
            msg: msg
        }));
    });
});


//用户换肤
app.post("/user/setUserOpts", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var userId = userInfo.id,
            userOpts = req.body.userOpts;
        userService.setUserOpts(userId, userOpts);
        res.send();
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

app.get("/user/setToken/:channel", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    userService.setToken(req, res);
});
app.get("/user/getToken/:channel", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    userService.getToken(req, res);
});
app.get("/user/codeLogin/:channel", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    userService.codeLogin(req, res);
});


app.post("/storage/save", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo,
        content = req.body.content;
    if (!userInfo) {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    } else if (content.length > 20 * 1024 * 1024) {
        res.send(JSON.stringify({
            result: -2,
            msg: "文件大小超过限制，上限为20MB。"
        }));
    } else {
        var thumbnail = req.body.thumbnail;
        projectService.saveProj(userInfo.id, content, thumbnail, function (ret) {
            res.send(ret);
        });
    }

});
app.get("/storage/list", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (!userInfo) {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    } else {
        var userId = userInfo.id;
        projectService.getUserProjList(userId, function (list) {
            //这里先添加一个项目上限
            userService.getUserLimit(userId, function (limitNum) {
                res.send(JSON.stringify({
                    result: 0,
                    limitNum: limitNum,
                    list: list
                }));
            });
        });
    }
});

//获取自己的工程信息
app.get("/storage/project/:projId", function (req, res) {
    var userInfo = req.session.userInfo;
    if (!userInfo) {
        res.status(403);
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    } else {
        var userId = userInfo.id,
            projId = req.params.projId;
        projectService.getProjById(userId, projId, function (ret) {
            res.send(JSON.stringify(ret));
        });
    }
});

app.get("/storage/remove/:id", function (req, res) {
    var userInfo = req.session.userInfo;
    if (!userInfo) {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    } else {
        var id = req.params.id;
        var userId = userInfo.id;
        projectService.removeProjById(id, userId, function (err) {
            if (err) {
                res.send(JSON.stringify({
                    result: -1,
                    list: err
                }));
                return;
            }
            res.send(JSON.stringify({
                result: 0
            }));
        });
    }
});

app.get("/storage/updateVisitNum", function (req, res) {
    res.send(JSON.stringify({
        result: 0,
        // msg: ""
    }));
    projectService.updateVisitNum(req.query.id, req.query.userId);
});
//编译
app.post("/hardware/codeCompile", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    let code = req.body.code;
    if (!code) {
        res.send(JSON.stringify({
            result: -1,
            msg: "硬件代码有误"
        }));
    } else if (code.length > 20 * 1024 * 1024) {
        res.send(JSON.stringify({
            result: -1,
            msg: "文件大小超过限制，上限为20MB。"
        }));
    } else {
        compileService.compileCode(req, res);
    }
});

//*******************聚合平台作品相关接口*********************

app.get("/storage/getProjTemplete/:contestId/:uid", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var userId = req.params.uid;
    if (userId && userId !== "undefined") {
        var contestId = req.params.contestId ? req.params.contestId : 1;
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        projectService.addProjTemplete(contestId, userId, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//聚合用户查看个人作品列表接口 后台调用  
app.get("/storage/listbyuid/:uid/:offset/:limit", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    // res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET,HEAD, PUT, POST, PATCH,DELETE,OPTIONS");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var userId = req.params.uid,
        offset = req.params.offset, //请求偏移量
        limit = req.params.limit; //每页的数量
    if (userId && userId !== "undefined" && offset && limit) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        //先这样 安全在线等检查要加  FIXME 程绪
        // var _callback = req.query.callback;
        // if (userId && _callback) {
        // 	userId = "juhe_" + userId;
        // 	res.type('text/javascript');
        // 	projectService.getUserProjList(userId, function (list) {
        // 		//这里先添加一个项目上限
        // 		userService.getUserLimit(userId, function (limitNum) {
        // 			res.send(_callback + '(' + JSON.stringify({
        // 				result: 0,
        // 				limitNum: limitNum,
        // 				list: list
        // 			}) + ')');
        // 		});
        // 	});
        // } else {
        projectService.getUserProjListByPage(userId, offset, limit, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "获取失败!"
        }));
    }
});

//聚合平台获取自己的工程信息 暂没有权限验证
app.get("/storage/getUserProjByPid", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");

    var projId = req.query.projId;
    //	console.log(projId);
    if (projId) {
        projectService.getUserProjByPid(projId, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "查看失败"
        }));
    }
});

//聚合分享或者更新分享  保留历史版本 
app.get("/storage/juheShareProj", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    // res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET,HEAD, PUT, POST, PATCH,DELETE,OPTIONS");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var userId = req.query.uid;
    var projId = req.query.projInfo.projId;
    if (userId && userId !== "undefined" && projId) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        projectService.juheShareProj(userId, projId, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "分享失败"
        }));
    }
});

//聚合小组发帖分享
app.get("/storage/groupShareProj/:uid/:projId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    // res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET,HEAD, PUT, POST, PATCH,DELETE,OPTIONS");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var userId = req.params.uid,
        projId = req.params.projId;
    if (userId && userId !== "undefined" && projId) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        projectService.juheGroupShareProj(userId, projId, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "分享失败"
        }));
    }
});

//聚合获取分享的工程列表
app.get("/storage/listJuheShareProjByPage/:uid/:offset/:limit", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    // res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET,HEAD, PUT, POST, PATCH,DELETE,OPTIONS");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");

    var userId = req.params.uid,
        offset = req.params.offset, //请求偏移量
        limit = req.params.limit; //每页的数量
    if (userId && userId !== "undefined" && offset && limit) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        projectService.getJuheShareProListjByPage(userId, offset, limit, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "获取列表失败"
        }));
    }
});

//聚合获取分享的历史版本
app.get("/storage/listJuheShareHistoryProjByPage/:uid/:projId/:offset/:limit", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    // res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET,HEAD, PUT, POST, PATCH,DELETE,OPTIONS");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");

    var userId = req.params.uid,
        projId = req.params.projId,
        offset = req.params.offset, //请求偏移量
        limit = req.params.limit; //每页的数量
    if (userId && userId !== "undefined" && projId && offset && limit) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        projectService.listJuheShareHistoryProjByPage(userId, projId, offset, limit, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "获取列表失败"
        }));
    }
});

//聚合获取分享后改编的作品
app.get("/storage/getJuheShareAdaptListByPage/:uid/:jhShareId/:offset/:limit", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    // res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET,HEAD, PUT, POST, PATCH,DELETE,OPTIONS");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");

    var userId = req.params.uid,
        fromShareId = req.params.jhShareId,
        offset = req.params.offset, //请求偏移量
        limit = req.params.limit; //每页的数量
    if (userId && userId !== "undefined" && fromShareId && offset && limit) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        projectService.getJuheShareAdaptListByPage(userId, fromShareId, offset, limit, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "获取列表失败"
        }));
    }
});

//聚合取消分享
app.get("/storage/cancleShareProj", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");

    var userId = req.query.uid;
    var projId = req.query.projInfo.projId;

    if (userId && userId !== "undefined" && projId) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        projectService.cancleShareProj(userId, projId, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "取消分享失败"
        }));
    }
});

//聚合更新源文件
app.get("/storage/updateShareSource", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
    res.setHeader("Access-Control-Allow-Methods", "POST");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var userId = req.query.uid;
    var projInfo = req.query.projInfo;
    if (userId && userId !== "undefined" && projInfo) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        projectService.updateShareSource(userId, projInfo, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "更新失败"
        }));
    }
})

//聚合查看分享    
app.get("/storage/viewShareProjByPid/:shareId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var shareId = req.params.shareId;
    if (shareId) {
        projectService.viewShareProjByPid(shareId, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "查看分享失败"
        }));
    }
});

//聚合查看小组分享
app.get("/storage/viewJuheGroupShareProjByPid/:projId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    // res.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var projId = req.params.projId;
    if (projId) {
        projectService.viewJuheGroupShareProjByPid(projId, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "查看失败"
        }));
    }
});

//===========================================以下是新加的课程接口=======================================================//
//创建课程目录
app.get("/course/createCourseset", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    //验证用户的有效性
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var userId = userInfo.id;
        //	var userId = "juhe_d04cd7e2-0c18-428d-b110-5859faf0f19c";
        courseService.createCourseset(userId, function (ret) {
            res.send(ret);
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//获取课程目录列表
app.get("/course/getCoursesetList", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var userId = userInfo.id;
        //			var userId = "juhe_d04cd7e2-0c18-428d-b110-5859faf0f19c";
        courseService.getCoursesetList(userId, function (ret) {
            res.send(ret);
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//保存课程目录名字
app.post("/course/coursesetNameSave", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var coursesetInfo = req.body;
        //	coursesetInfo = {
        //		coursesetId: 4,
        //		coursesetName: "诺丁课程"
        //	}
        if (coursesetInfo) {
            var userId = userInfo.id;
            //		var userId = "juhe_d04cd7e2-0c18-428d-b110-5859faf0f19c";
            courseService.coursesetNameSave(userId, coursesetInfo, function (ret) {
                res.send(ret);
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "保存出错"
            }));
        }
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//删除课程目录
app.get("/course/delCourseset/:coursesetId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var coursesetId = req.params.coursesetId;
        if (coursesetId) {
            var userId = userInfo.id;
            //	var userId = "juhe_d04cd7e2-0c18-428d-b110-5859faf0f19c";
            courseService.delCourseset(userId, coursesetId, function (ret) {
                res.send(ret);
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "删除失败"
            }));
        }
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//移动课程到相应的目录
app.post("/course/moveToCourseset", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var coursesetInfo = req.body;
        //			coursesetInfo = {
        //				"courseId": "92", //课程id
        //				"oldCoursesetId": "83", //原有的课程目录id（删除）
        //				"newCoursesetId": "2" //新的课程目录的id（添加）
        //			}
        if (coursesetInfo) {
            var userId = userInfo.id;
            //			var userId = "juhe_d04cd7e2-0c18-428d-b110-5859faf0f19c";
            courseService.moveToCourseset(userId, coursesetInfo, function (ret) {
                res.send(ret);
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "移动失败"
            }));
        }
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//移动排序
app.post("/course/changeOrder", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var coursesetInfo = req.body;
        //	coursesetInfo = {
        //		"coursesetId": "5", //课程目录id
        //		"courseId": "10", //当前的课程id
        //		"orderType": 0 //移动的顺序,0是上移,1是下移,2是置顶,3是置底
        //	}
        if (coursesetInfo) {
            var userId = userInfo.id;
            //		var userId = "juhe_7f22a006-4c7f-4520-aaff-1a09977736b2";
            courseService.changeOrder(userId, coursesetInfo, function (ret) {
                res.send(ret);
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "移动失败"
            }));
        }
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//触发该接口（创建）获取自增id及相应的字段
app.get("/course/create/:coursesetId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var coursesetId = req.params.coursesetId;
        if (coursesetId) {
            var userId = userInfo.id;
            //		var userId = "juhe_d04cd7e2-0c18-428d-b110-5859faf0f19c";
            courseService.createCourse(userId, coursesetId, function (ret) {
                res.send(ret);
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "创建失败"
            }));
        }

    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//触发保存接口
app.post("/course/save", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var sectionInfo = req.body;
        if (sectionInfo) {
            var userId = userInfo.id;
            //					sectionInfo = {
            //				    "courseName": "323d",
            //                  "coursesetId": 1,
            //				    "courseId": "8",
            //				    "titleType": "0",
            //			        "sectionNum": "0",
            //			        "sectionName": "",
            //			        "sectionContent": "123"
            //			   }
            courseService.saveSection(userId, sectionInfo, function (ret) {
                res.send(ret);
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "保存失败"
            }));
        }
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//触发该接口保存课程名和章节名
app.post("/course/courseNameSave", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var courseInfo = req.body;
        if (courseInfo) {
            var userId = userInfo.id;
            courseService.courseNameSave(userId, courseInfo, function (ret) {
                res.send(ret);
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "保存出错"
            }));
        }
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//触发该接口保存课程名和章节名
app.post("/course/sectionNameSave", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var sectionInfo = req.body;
        if (sectionInfo) {
            var userId = userInfo.id;
            courseService.sectionNameSave(userId, sectionInfo, function (ret) {
                res.send(ret);
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "保存出错"
            }));
        }
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//触发该接口md5校验内容的是否相同
app.post("/course/sectionContentVerify", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var sectionInfo = req.body;
        if (sectionInfo) {
            var userId = userInfo.id;
            courseService.sectionContentVerify(userId, sectionInfo, function (ret) {
                res.send(ret);
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "校验错误"
            }));
        }
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//触发该接口删除用户下对应的课程信息
app.get("/course/remove/:coursesetId/:courseId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var coursesetId = req.params.coursesetId;
        var courseId = req.params.courseId;
        if (courseId && coursesetId) {
            var userId = userInfo.id;
            //			var userId = "juhe_d04cd7e2-0c18-428d-b110-5859faf0f19c";
            courseService.removeCourseById(userId, coursesetId, courseId, function (ret) {
                res.send(ret);
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "删除失败"
            }));
        }
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//添加章节（更新）接口
app.post("/course/createSection", function (req, res) {
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var sectionInfo = req.body;
        if (sectionInfo) {
            var userId = userInfo.id;
            courseService.createSection(userId, sectionInfo, function (ret) {
                res.send(ret);
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "创建章节失败"
            }));
        }

    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));

    }
});

//删除章节（更新）接口
app.post("/course/removeSection", function (req, res) {
    var userInfo = req.session.userInfo;
    if (userInfo) {
        var sectionInfo = req.body;
        //			sectionInfo = {
        //              "coursesetId": "18",
        //				"courseId": "18",
        //				"titleType": "0",
        //				"sectionNum": "0"
        //			};
        if (sectionInfo) {
            var userId = userInfo.id;
            courseService.removeSection(userId, sectionInfo, function (ret) {
                res.send(ret);
            });
        } else {
            res.send(JSON.stringify({
                result: -1,
                msg: "删除章节失败"
            }));
        }
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));

    }
});

//触发该接口 获取课程章节列表,0代表本地课程，1代表待审核课程（管理员查看），2代表审核通过的课程(查看侧边栏用)
app.get("/course/viewCourseList/:courseListType/:coursesetId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    let userInfo = req.session.userInfo;
    // if(userInfo) {
    // 	var userId = userInfo.id,
    //	var userId="juhe_03fef7ae-2cf9-48c3-bc76-27d10cc46585",
    let courseListType = req.params.courseListType, //章节类型
        coursesetId = req.params.coursesetId;
    if (courseListType && coursesetId) {
        if (courseListType == 0) {
            courseService.viewCourseList(userInfo, coursesetId, function (ret) {
                res.send(ret);
            });
        } else if (courseListType == 1) {
            courseService.viewReleaseCoursesetList(userInfo, coursesetId, function (ret) {
                res.send(ret);
            });
        } else {
            courseService.viewSuccessCoursesetList(userInfo, coursesetId, function (ret) {
                res.send(ret);
            });
        }

    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "查看失败"
        }));
    }
    // } else {
    // 	res.send(JSON.stringify({
    // 		result: -1,
    // 		msg: "未登录"
    // 	}));
    // }
});

//触发该接口（获取章节中的内容），0代表本地课程，1代表待审核课程（管理员查看），2代表审核通过的课程（查看侧边栏用）
app.get("/course/viewCourseById/:courseContentType/:coursesetId/:courseId", function (req, res) {
    var userInfo = req.session.userInfo;
    // if(userInfo) {
    // 	var userId = userInfo.id,
    //					var userId="juhe_03fef7ae-2cf9-48c3-bc76-27d10cc46585",
    var courseContentType = req.params.courseContentType, //章节内容类型
        coursesetId = req.params.coursesetId,
        courseId = req.params.courseId;
    if (courseContentType && courseId && coursesetId) {
        if (courseContentType == 0) {
            courseService.viewCourseById(userInfo, coursesetId, courseId, function (ret) {
                res.send(ret);
            });
        } else if (courseContentType == 1) {
            courseService.viewReleaseCourseById(userInfo, coursesetId, courseId, function (ret) {
                res.send(ret);
            });
        } else {
            courseService.viewSuccessCourseById(userInfo, coursesetId, courseId, function (ret) {
                res.send(ret);
            });
        }

    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "查看失败"
        }));
    }
    // } else {
    // 	res.send(JSON.stringify({
    // 		result: -1,
    // 		msg: "您尚未登录，请登录后查看"
    // 	}));
    // }
});

//获取发布课程用户权限  1
app.get("/course/getPublishCoursePermission", function (req, res) {
    if (req.session.userInfo) {
        var userId = req.session.userInfo.id;
        //var userId = "juhe_d04cd7e2-0c18-428d-b110-5859faf0f19c";
        // var permissionType = "DEPLOY_COURSE"; //
        userService.getUserPermission(userId, function (ret) {
            res.send(ret);
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "未登录"
        }));
    }
});

//上传教案接口，需要有上传教案的权限 2
app.post('/course/uploadFile', function (req, res) {
    upload(req, res, function (err) {
        if (err) {
            console.error("上传失败");
            res.send(JSON.stringify({
                result: -1,
                desc: "上传失败 "
            }));
            //			return;
        } else {
            res.send(JSON.stringify({
                result: 0,
                desc: "上传成功"
            }));
        }

    });
});

//==============================================聚合平台对接课程接口=======================================//
//聚合平台用户分页获取未发布课程集合列表
app.get("/course/getUnpublishedCourseList/:uid/:offset/:limit", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var userId = req.params.uid;
    var offset = req.params.offset;
    var limit = req.params.limit; //请求的每页数量
    if (userId && userId !== "undefined" && offset && limit) {
        // userId = "juhe_" + userId;
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        //		console.log(host + "//////////" + userId);
        courseService.getUnpublishedCourseListByUid(userId, offset, limit, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: " 获取课程集合列表失败"
        }));
    }
});

//聚合平台发布课程会将本地课程发送到待审核表中
app.get("/course/publish/:uid/:rePublishFlag", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var userId = req.params.uid,
        rePublishFlag = req.params.rePublishFlag, //1是更新发布，就是需将审核通过表中的数据放入待审核表中,0就是不更新只是将本地课程放入待审核表中
        courseInfo = req.body.courseInfo;
    //		courseInfo = {
    //			coursesetId: 4, //课程集合的id
    //			courseType: 1, //课程类型,0是免费课程,1是收费课程,2是线下课程
    //			sectionFeeFlag: { "10": 0, "11": 1 } //如果不存在免费章节(也就是说全是收费章节都为1的情况)就不要传sectionFeeFlag这个参数
    //		};
    if (userId && userId !== "undefined" && rePublishFlag && courseInfo) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        courseService.publishCourse(userId, rePublishFlag, courseInfo, function (ret) {
            res.send(JSON.stringify(ret));
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "发布失败"
        }));
    }
});

//聚合平台取消发布课程
app.get("/course/unPublish/:uid/:coursesetId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var userId = req.params.uid;
    var coursesetId = req.params.coursesetId;
    if (userId && userId !== "undefined" && coursesetId) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        courseService.unPublishCourse(userId, coursesetId, function (ret) {
            res.send(ret);
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "取消失败"
        }));
    }
});

//聚合平台触发该接口更新（或插入到）审核通过表(course_list_success),以及(删除并插入)course_success表
app.get("/course/approvalCourse/:coursesetId/:action", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var coursesetId = req.params.coursesetId;
    var action = req.params.action;
    if (action && coursesetId) {
        courseService.approvalCourse(coursesetId, action, function (ret) {
            res.send(ret);
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "审核失败"
        }));
    }

});

//聚合平台购买整本书成功之后 回调接口
app.get("/course/purchaseSuccess/:uid/:coursesetId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var userId = req.params.uid;
    var coursesetId = req.params.coursesetId;
    console.log("用户聚合购买课程成功回调编辑器,用户id/" + userId + "/课程id/" + coursesetId);
    if (userId && userId !== "undefined" && coursesetId) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        courseService.purchaseSuccess(userId, coursesetId, function (ret) {
            res.send(ret);
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "购买课程失败"
        }));
    }

});

//触发该接口设置用户权限，0代表管理员权限,1代表时发布课程权限,2是上传教案的权限
app.post("/course/updateUserPermission/:uid", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "POST");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var userId = req.params.uid;
    var permissionTypes = req.body.permissionTypes;
    console.log("该用户具有的用户权限为：" + permissionTypes);
    //	var	permissionTypes = [0, 1, 2];
    if (userId && userId !== "undefined" && permissionTypes) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        userService.updateUserPermission(userId, permissionTypes, function (ret) {
            res.send(ret);
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "设置用户权限失败"
        }));
    }

});

//聚合查看课程目录,0是查看本地课程，1是查看待审核中的课程，2是查看审核通过的课程
app.get("/course/getCourseCategory/:categoryType/:coursesetId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var categoryType = req.params.categoryType; //目录类型0是查看本地课程，1是查看待审核中的课程，2是查看审核通过的课程
    var coursesetId = req.params.coursesetId;
    if (categoryType && coursesetId) {
        if (categoryType == 0) {
            courseService.getCoursesetAll(coursesetId, function (ret) {
                res.send(ret);
            });
        } else if (categoryType == 1) {
            courseService.getReleaseCoursesetAll(coursesetId, function (ret) {
                res.send(ret);
            });
        } else {
            courseService.getSuccessCoursesetAll(coursesetId, function (ret) {
                res.send(ret);
            });
        }

    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "查看失败"
        }));
    }
});

//聚合平台用户下架已发布的课程
app.get("/course/unPublishSucessCourse/:uid/:coursesetId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var userId = req.params.uid;
    var coursesetId = req.params.coursesetId;
    console.log("用户下架课程" + userId + "/" + coursesetId);
    if (userId && userId !== "undefined" && coursesetId) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        courseService.unPublishSucessCourse(userId, coursesetId, function (ret) {
            res.send(ret);
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "查看失败"
        }));
    }
});

//聚合平台管理员取消用户已购买的课程时验证成功性
app.get("/course/canclePurchasedCourse/:uid/:coursesetId", function (req, res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Vary", "*");
    res.setHeader("Access-Control-Allow-Origin", req.headers["origin"] || req.headers["host"]);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    var userId = req.params.uid;
    var coursesetId = req.params.coursesetId;
    if (userId && userId !== "undefined" && coursesetId) {
        var host = req.hostname;
        userId = userService.getUserIdByHost(host, userId);
        courseService.canclePurchasedCourse(userId, coursesetId, function (ret) {
            res.send(ret);
        });
    } else {
        res.send(JSON.stringify({
            result: -1,
            msg: "取消失败"
        }));
    }
});

//===========================================================================//
app.listen(config.httpPort, function () {
    console.log('Example app listening on port ' + config.httpPort);
});

function setCustomCacheControl(res, path) {
    // if (serveStatic.mime.lookup(path) === 'text/html') {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET");
    res.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type");
    // }
}